<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ivan
 * Date: 8/23/12
 * Time: 5:08 PM
 * To change this template use File | Settings | File Templates.
 */

class Page_Be_Cms_Menus extends Page {

	/**
	 * @var Db_Cms_Menus
	 */
	protected $tableObject;

	function __construct() {
        self::$TPL->appendCssFile('admin/menus');
        self::$TPL->appendJsFile('admin/menus');
		$this->actionsTableObject = array('saveAction', 'configItemsAction', 'addEditItemAction', 'addEditAction');
		$this->classTableObject = 'Db_Cms_Menus';
		$this->idTableObject = get('id', 'int');
		parent::__construct();


	}

	public function defaultAction() {
        if (perm('MENUS_EDIT')) {
            $this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit');
        }
		$allMenus = Db_Cms_Menus::findAllArray();
		self::$TPL->assign('allMenus', $allMenus);
		self::$TPL->setBodyTemplate('list_menus');
		return array(
			'type' => 'display'
		);
	}

	public function addEditAction() {
        perm('MENUS_EDIT', self::$PAGE['p_url']);
		if(isset($this->tableObject->objectArray->id)) {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' &quot;' . t(T_MENU_TITLE, $this->tableObject->objectArray->m_title) . '&quot;', '?action=addEdit', true);
		} else {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit', true);
		}
		$allProjects = Db_Projects::getDistinctProjects();
		self::$TPL->assign('menuObj',$this->tableObject->objectArray);
		self::$TPL->assign('allProjects', $allProjects);
		self::$TPL->setBodyTemplate('add_edit_menu');
		return array(
			'type' => 'display'
		);
	}

	public function saveAction() {
		perm('MENUS_EDIT', self::$PAGE['p_url']);
		$projectIdentifier = strtolower(post('m_project_identifier', 'string'));
		$menuTitle = strtolower(post('m_title', 'string'));
		$menuIdentifier = strtolower(post('m_identifier', 'string'));
		if($this->tableObject->objectArray->id) {
			$countMenuItems = Db_Cms_MenuPages::countAllByField('mp_menu_id', $this->tableObject->objectArray->id);
			if ($countMenuItems > 0 && $this->tableObject->objectArray->m_project_identifier != $projectIdentifier) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'cannot_change_project');
			}
		}
		if (!empty($projectIdentifier) && !empty($menuTitle) && !empty($menuIdentifier) && !$this->error) {

			$this->tableObject->m_project_identifier = $projectIdentifier;
			$this->tableObject->m_title = $menuTitle;
			$this->tableObject->m_identifier = $menuIdentifier;
			$this->tableObject->m_template = strtolower(post('m_template', 'str'));
			if (!$this->tableObject->save(true)) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			} else {
				$this->message = t(T_FORM_MSG, 'success');
			}
		} else if (!$this->error) {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'required_fields');
		}
		Db_Cms_Pages::updateProductPageUrls();
		return array(
			'type' => 'redirect',
			'query' => false
		);
	}

	public function configItemsAction() {
        perm('MENUS_EDIT', '/cms/menus');
		$this->addBreadcrumb(t(T_PAGE_TITLE, 'menus_items') . ' &quot;' . t(T_MENU_TITLE, $this->tableObject->objectArray->m_title) . '&quot;', '?action=configItems&id='. $this->tableObject->objectArray->id, true);
		$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEditItem&id='.$this->tableObject->objectArray->id);

		if ($this->tableObject->objectArray->id) {
			$allItems = Db_Cms_Menus::getItemsById($this->tableObject->objectArray->id);

			if ($allItems) {
				$items = Menus::createTreeMenus($allItems);
				self::$TPL->assign('items', $items);
			}
			self::$TPL->assign('menuObject', $this->tableObject->objectArray);
			self::$TPL->setBodyTemplate('show_menu_items');

			return array(
				'type' => 'display'
			);
		}
		$this->message = t(T_ERROR_MESSAGE, 'missing_record');
		$this->error = true;
		return array(
			'type' => 'redirect',
			'query' => false
		);
 	}

	/**
	 * @return array
	 * form for add/edit page item in menu
	 */
	public function addEditItemAction() {
		perm('MENUS_EDIT', self::$PAGE['p_url']);
        $this->addBreadcrumb(t(T_PAGE_TITLE, 'menus_items') .' &quot;' . t(T_MENU_TITLE, $this->tableObject->objectArray->m_title) . '&quot;', '?action=configItems&id='. get('id', 'int'));
        $menuPageId = get('menu_page_id', 'int');
		$menuPagesObj = new Db_Cms_MenuPages($menuPageId);

		if (!$this->tableObject->objectArray->id) {

			$this->message = t(T_MESSAGE_RESULT, 'no_data');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'content' => '?'
			);
		}
        if (get('menu_page_id', 'int')) {
			$titleForBreadcrumb = ($menuPagesObj->objectArray->mp_item_title) ? t(T_MENU_LABEL, $menuPagesObj->objectArray->mp_item_title) : $menuPagesObj->objectArray->id;
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' &quot;' .$titleForBreadcrumb. '&quot;' , '?action=addEditItem&id='. get('id', 'int')."&menu_page_id=".get('menu_page_id', 'int'), true);
        } else {
            $this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEditItem&id='. get('id', 'int'), true);
        }
		self::$TPL->assign('menuPageItem', $menuPagesObj->objectArray);
		self::$TPL->assign('menuObj', $this->tableObject->objectArray);
		self::$TPL->setBodyTemplate('add_edit_menu_item');

		$menuList = $this->tableObject->findAllArray();
		$parentPageList = Db_Cms_MenuPages::getPagesByMenuId($this->tableObject->objectArray->id, ($menuPagesObj->objectArray? $menuPagesObj->objectArray->mp_page_id : false));

		self::$TPL->assign('menuList', $menuList);
		self::$TPL->assign('parentPageList', $parentPageList);
		$pagesList = Db_Cms_Pages::getElementsForSelect('p_name');
		self::$TPL->assign('pagesList',$pagesList);
		return array(
			'type' => 'display'
		);

	}

	/**
	 * @return array
	 * save item in menu
	 */
	public function saveItemAction() {
		perm('MENUS_EDIT', self::$PAGE['p_url']);
		$pageId = post('mp_page_id', 'int');
		$menuId = get('id', 'int');
		$projects = array();
		$inProjects = Db_Projects::getProjectsIdentifierByMenus(array($menuId));
		$page = Db_Cms_Pages::findById($pageId);
		if ($page->p_pagination_type == "product") {
			if ($pageUsed = Db_Cms_Pages::checkPageIsUniqueInProjectByType('product', $pageId, $inProjects)) {
				foreach ($pageUsed as $project) {
					$projects[] = ct(T_PROJECT_TITLE, $project['pr_identifier']);
				}
				$this->message = t(T_FORM_ERROR, 'page_types_product_already_exists'). " " . implode(', ', $projects);
				$this->error = true;
				return array(
					'type' => 'redirect',
					'content' => '?action=configItems&id='.$menuId
				);
			}
		}

		$menuPageId = get('menu_page_id', 'int');

		$menuPagesObj = new Db_Cms_MenuPages($menuPageId);

        $oldParentId = $menuPagesObj->objectArray->mp_parent_id;
		$parentId = post('mp_parent_id', 'int');

		if((!$menuPagesObj->checkParentExistInMenu($parentId, $menuId)) ||
			($menuPagesObj->checkForDuplicate($menuPageId, $menuId, $pageId)) || $pageId == $parentId) {
			$this->message = t(T_MESSAGE_RESULT,'incorrect_data');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'content' => '?action=addEditItem&id='.$menuId //.'&menu_page_id='.$menuPageId
			);
		}

		$menuPagesObj->mp_menu_id = $menuId;
		$menuPagesObj->mp_page_id = $pageId;
		$menuPagesObj->mp_item_title = post('mp_item_title', 'str');
		$menuPagesObj->mp_item_icon = post('mp_item_icon', 'str');
		$menuPagesObj->mp_parent_id = $parentId;
		$menuPagesObj->mp_display = post('mp_display', 'int');
		if ($menuPagesObj->save(true)) {
			$menuPagesObj->positionCommonFields = array('mp_menu_id'=>$menuId, 'mp_parent_id'=>$parentId);
            if ($oldParentId != $parentId || $menuPageId == 0) {
                $menuPagesObj->positionCleanUp();
                $menuPagesObj->positionSetLast();
            }
			Db_Cms_Pages::updateProductPageUrls();
			$this->message = t(T_FORM_MSG, 'success');
			return array(
				'type' => 'redirect',
				'content' => '?action=addEditItem&id='.$menuId.'&menu_page_id='.$menuPagesObj->id
			);
		} else {
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'content' => '?action=configItems&id='.$menuId
			);
		}
	}

    public function deleteAction() {
		perm('MENUS_EDIT', self::$PAGE['p_url']);
        $this->message = t(T_FORM_MSG, 'success');
        if(!Db_Cms_Menus::abstractDelete($this->idTableObject)) {
            $this->error = true;
            $this->message = t(T_FORM_MSG, 'unknown_error_occurred');
        }
		Db_Cms_Pages::updateProductPageUrls();
        return array(
            'type' => 'redirect',
            'query' => false
        );
    }

	/**
	 * @return array
	 */
	public function deleteMenuItemAction() {
		perm('MENUS_EDIT', self::$PAGE['p_url']);
		$menuPagesObj = new Db_Cms_MenuPages(get('menu_page_id', 'int'));
		if (!$menuPagesObj->objectArray->id) {
			$this->message = t(T_FORM_MSG, 'delete_msg_false');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'content' => '?c'
			);
		}

		if ($menuPagesObj->deleteByField('id', $menuPagesObj->objectArray->id)) {
			Db_Cms_Pages::deleteAllChildrenPage($menuPagesObj->objectArray->mp_page_id);
			$menuPagesObj->positionCleanUp();
			$this->message = t(T_FORM_MSG, 'delete_msg_true');
			Db_Cms_Pages::updateProductPageUrls();
			return array(
				'type' => 'redirect',
				'content' => '?action=configItems&id='.get('id', 'int')
			);
		} else {
			$this->message = t(T_FORM_MSG, 'delete_msg_false');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'content' => '?'
			);
		}
	}


	/**
	 * function for change position of page in menu
	 */
	public function ajaxSavePagePositionAction() {

		$menuPageId = post('menuPageId', 'int');

		$menuPagesObj = new Db_Cms_MenuPages($menuPageId);
		$menuPagesObj->positionCommonFields = array('mp_menu_id' => $menuPagesObj->objectArray->mp_menu_id, 'mp_parent_id' => $menuPagesObj->objectArray->mp_parent_id);

		$btnAction = post('btnAction', 'string');
		//$menuPagesObj->positionCleanUp();

		return $this->moveUpDownAjax($btnAction, $menuPagesObj);

	}

	/**
	 * @return array
	 */
	public function ajaxGetPagesByMenuIdAction() {
		$menuId = post('menuId', 'int');
		$mpPageId = post('menuPageId', 'int');
		$pages = Db_Cms_MenuPages::getPagesByMenuId($menuId, $mpPageId);
		self::$TPL->assign('pages', $pages);
		return array(
			'type' => 'json',
			'content' => self::$TPL->display('parent_page_options', true)
		);
	}


}
